package com.example.edwinanimation

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.os.Bundle
import android.util.Log
import android.view.animation.AccelerateInterpolator
import android.view.animation.CycleInterpolator
import android.view.animation.OvershootInterpolator
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.example.edwinanimation.databinding.ActivityMainBinding
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 晃动次数
 * 一次的动画序列
 * 插值器：平滑、先快后慢、匀速
 */
class MainActivity3 : AppCompatActivity() {
    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        // 确保视图已完成布局
        binding.ivAnimation.post {
            // 设置旋转中心为底部居中
            binding.ivAnimation.pivotX = binding.ivAnimation.width / 2f
            binding.ivAnimation.pivotY = binding.ivAnimation.height.toFloat()

            lifecycleScope.launch {
                wobbleAnimation.startDelay = 1500
                wobbleAnimation.start()
            }
        }
    }


    //左右抖动动画。
    private val wobbleAnimation: ObjectAnimator by lazy {
        // 创建旋转动画对象
        // 该动画将操作 binding.ivAnimation 视图的 "rotation" 属性
        ObjectAnimator.ofFloat(
            binding.ivAnimation, "rotation", // 目标视图 要操作的属性（旋转角度）
            0f, 3f, -3f, 0f
        ).apply {
            duration = 200// 设置整一次序列动画的时长
            repeatCount = 9 //设置执行次数
            interpolator = AccelerateInterpolator()
        }
    }
}

